package net.esj.basic.core.engine.tools.crypt;

import java.security.NoSuchAlgorithmException;

import org.springframework.util.Assert;

import net.esj.basic.core.engine.support.UnsupportedRunTimeException;
import net.esj.basic.utils.StringUtils;

public class MD5CryptImpl implements UnilateralCrypt {

	@Override
	public boolean checksum(byte[] bytes, byte[] encryptPass, byte[] results) {
		Assert.notNull(results);
		byte[] encrypts = encrypt(bytes, encryptPass);
		
		if(encrypts.length != results.length){
			return false;
		}
		for(int i=0;i<encrypts.length;i++){
			if(encrypts[i] != results[i]){
				return false;
			}
		}
		return true;
	}

	@Override
	public boolean checksum(byte[] bytes, byte[] results) {
		return checksum(bytes,  results);
	}

	@Override
	public boolean checksum(String content, byte[] encryptPass, String results) {
		return checksum(content, encryptPass, results);
	}

	@Override
	public boolean checksum(String content, String results) {
		Assert.notNull(results);
		String encrypts = encrypt(content);
		
		if(results.equals(encrypts)){
			return true;
		}
		return false;
	}

	@Override
	public byte[] decrypt(byte[] bytes) {
		throw new UnsupportedRunTimeException("单向加密不支持解密程式!!!");
	}

	@Override
	public byte[] decrypt(byte[] bytes, byte[] decryptPass) {
		throw new UnsupportedRunTimeException("单向加密不支持解密程式!!!");
	}

	@Override
	public String decrypt(String content) {
		throw new UnsupportedRunTimeException("单向加密不支持解密程式!!!");
	}

	@Override
	public String decrypt(String content, byte[] decryptPass) {
		throw new UnsupportedRunTimeException("单向加密不支持解密程式!!!");
	}

	@Override
	public byte[] encrypt(byte[] bytes) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest
				.getInstance("MD5");
			md.update(bytes);
			byte tmp[] = md.digest();
			return tmp;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public byte[] encrypt(byte[] bytes, byte[] encryptPass) {
		return encrypt(bytes);
	}

	@Override
	public String encrypt(String content) {
		byte[] bytes = content.getBytes();
		byte[] crypts = encrypt(bytes);
		return StringUtils.parseByte2HexStr(crypts);
	}

	@Override
	public String encrypt(String content, byte[] encryptPass) {
		return encrypt(content);
	}

	@Override
	public void setDefaultSecretKey(String key) {
		
	}

	public static void main(String[] args){
		MD5CryptImpl crypt = new MD5CryptImpl();
		System.out.println(crypt.encrypt("123456".getBytes()));
	}
}
